<template>
  <div style="width: 100%" class="fileBox">
    <div style="width: 100%">
      <el-form class="operation">
        <div style="float: left">
          <el-button
            type="default"
            size="small"
            @click="backUp"
          ><span>上一级</span></el-button>
          <el-button
            type="primary"
            size="small"
            @click="newFloderClick"
          ><span>新建文件夹</span></el-button>
          <!-- <el-button type="danger" size="small"><span>删除</span></el-button> -->
          <el-button
            type="default"
            size="small"
            @click="uploadFile"
          ><span>上传文件</span></el-button>
        </div>
        <div class="icon" style="float: right;">
          <i class="el-icon-tickets" @click="watchLog" />
          <!-- <span style="font-size:12px">操作日志</span> -->
        </div>
      </el-form>
      <div class="logDialog">
        <el-dialog title="文件操作日志" :visible.sync="logDialog" width="60%">
          <div class="selectDiv">
            <el-select
              v-model="selectLog"
              class="selectInput"
              placeholder=""
              @change="selectFileLog"
            >
              <el-option
                v-for="(item, index) in LogList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <el-scrollbar>
            <el-timeline class="timeLine">
              <el-timeline-item
                v-for="(item, index) in activities"
                :key="index"
                :icon="item.icon"
                :type="item.type"
                :color="item.color"
                :size="item.size"
                :timestamp="item.created_at"
              >
                {{ item.operator }} 在 <span>{{ item.file_path }}</span>
                <span>{{ item.operation_text }}</span>
                <span>{{ item.operation }}</span>
              </el-timeline-item>
            </el-timeline></el-scrollbar>
          <span slot="footer" class="dialog-footer">
            <el-button @click="canelLog">取 消</el-button>
          </span>
        </el-dialog>
      </div>
    </div>

    <el-dialog
      title="上传文件"
      :close-on-click-modal="false"
      :visible.sync="uploadFileDialog"
      width="500px"
    >
      <el-upload
        ref="upload"
        class="upload-input"
        drag
        action=""
        :on-exceed="handleExceed"
        :http-request="uploadSectionFile"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-error="handleError"
        :on-success="getFilePath"
        :headers="headers"
        :on-change="handleChangeFile"
        :before-upload="beforeUpload"
        :limit="3"
        :accept="limit_file_type.toString()"
        :auto-upload="false"
        :data="{ currentDirectory }"
      >
        <!-- :before-remove="beforeRemove" -->
        <!-- multiple -->
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击选择文件</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传<span style="color: red">{{
            limit_file_type.join("/").replace(/\./g, "")
          }}</span>文件，且单个文件不超过50MB
        </div>

        <!-- <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器</el-button
        > -->
      </el-upload>

      <el-form
        class="folder_fileNewname_form"
        label-width="200px"
        label-
        style="margin-top: 20px"
      >
        <span style="color: red">重命名</span>
        <el-form-item
          v-for="(item, i) in fileLists"
          :key="i"
          :label="'' + item.name"
        >
          <el-input
            v-model="file_new_names[item.uid]"
            placeholder="不输入则自动使用原名保存！"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取 消</el-button>
        <!-- <el-button type="primary" @click="confirmUpload">确 定</el-button> -->
        <el-button type="primary" @click="submitUpload">上 传</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="dialogTitle == '新建文件夹' ? '新建文件夹' : '上传文件'"
      :visible.sync="newFolderDialog"
      width="40%"
    >
      <el-form v-model="folderInfo">
        <el-form-item label="文件夹名称 * ">
          <el-input v-model="folderInfo.name" />
        </el-form-item>
        <el-form-item v-show="displayPer" label="分配角色 *">
          <el-checkbox-group v-model="folderInfo.roles">
            <el-checkbox
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFolder">取 消</el-button>
        <el-button type="primary" @click="confirmFolder">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="assignDialog" width="40%">
      <el-form v-model="assignPer">
        <el-form-item label="分配角色 *">
          <el-checkbox-group v-model="assignPer.roles">
            <el-checkbox
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.id"
            >
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelAssign">取 消</el-button>
        <el-button type="primary" @click="confirmAssign">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="重命名" :visible.sync="reNameDialog" width="40%">
      <el-input v-model="updateFileName" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="canelReName">取 消</el-button>
        <el-button type="primary" @click="confirmReName">确 定</el-button>
      </span>
    </el-dialog>

    <viewer
      ref="viewer"
      :images="images"
      class="viewer"
      style="width: 100px; boder: 1px solid red"
      @inited="inited"
    >
      <img
        v-for="(src, index) in images"
        :key="index"
        :src="src"
        class="image"
      >
    </viewer>
    <!-- <el-scrollbar style="width:100%;height: 300px"> -->

    <div class="container">
      <div
        v-for="(item, index) in fileList"
        :key="index"
        class="box"
        :class="item.active == 1 ? 'active' : ''"
        @click="changeBg(index)"
        @contextmenu="showMenu(item, index)"
        @dblclick="
          dbClick(item.directory, item.fileName, item.is_dir, index, item.type)
        "
      >
        <div class="iconBox">
          <img width="80" height="80" :src="getIconUrl(item.type)" alt="">
        </div>
        <div class="fileText">
          <span
            :title="item.fileName"
            style="
              white-space: nowrap;
              text-overflow: ellipsis;
              width: 100%;
              overflow: hidden;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              display: -webkit-box;
            "
          >{{ item.fileName }}</span>
        </div>

        <vue-context-menu
          :context-menu-data="contextMenuData"
          @downloadFile="downloadFile"
          @renameFile="renameFile"
          @deleteFile="deleteFile"
          @previewImg="previewImg"
          @AssignPermissions="AssignPermissions"
        />
      </div>
    </div>

    <el-dialog
      title="内容预览（仅供文本预览，不保证格式失真）"
      :visible.sync="preview_show"
      width="900px"
      :before-close="handleClosePreview"
      :class="show_pr_type == 'excel' ? 'show_excel' : ''"
    >
      <div style="border: 1px solid #eee; padding: 20px">
        <div v-if="show_pr_type == 'pdf'">
          <el-button
            :disabled="nowPdfPage <= 1"
            @click="nowPdfPage--"
          >上一页</el-button>
          <el-button
            :disabled="nowPdfPage >= pageCount"
            @click="nowPdfPage++"
          >下一页</el-button>
          {{ currentPage }} / {{ pageCount }}
          <pdf
            :src="pdf_url"
            :page="nowPdfPage"
            @num-pages="pageCount = $event"
            @page-loaded="currentPage = $event"
          />
        </div>

        <div
          v-if="show_pr_type == 'word'"
          class="viewHtml_box"
          style="background: white; min-height: 500px; padding: 10px"
          v-html="viewHtml.html"
        />

        <div
          v-if="show_pr_type == 'excel'"
          class="viewHtml_box"
          style="background: white; min-height: 500px; padding: 10px"
        >
          <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
          >
            <el-menu-item
              v-for="(e_titles, ei) in excel_tabales"
              :key="ei"
              :index="ei.toString()"
            >{{ e_titles.title }}</el-menu-item>
          </el-menu>

          <table>
            <tr
              v-for="(exc, i) in viewHtml.excel.data"
              :key="i"
              :class="i == 0 ? 'table-header' : ''"
            >
              <td v-for="(td, tdi) in exc" :key="tdi">
                {{ td }}
              </td>
            </tr>
          </table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview_show = false">取 消</el-button>
        <el-button
          type="primary"
          @click="preview_show = false"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import { getInfo, getRoles } from '@/api/user'
import {
  insertFolder,
  getFolder,
  openDirectory,
  backUpDirectory,
  insertFile,
  deleteFolder,
  updateFileName,
  requestURL,
  analysisExcel,
  updateAssign,
  selectRoles,
  selectFileLog
} from '@/api/folder'
import { getToken } from '@/utils/auth'
export default {
  components: {
    pdf
  },
  data() {
    return {
      activities: [],
      assignDialog: false, // 分配角色dialog
      logDialog: false, // 文件操作日志idialog
      selectLog: '1',
      LogList: [
        {
          value: '1',
          label: '今日记录'
        },
        {
          value: '2',
          label: '本周记录'
        },
        {
          value: '3',
          label: '本月记录'
        }
      ],
      assignPer: {
        roles: []
      }, // 分配角色表单
      file_types: {
        docx: ['doc', 'docx'],
        xlsx: ['xls', 'xlsx'],
        ppt: ['ppt', 'pptx'],
        jpg: ['jpg', 'jpeg'],
        zip: ['zip', 'rar'],
        txt: ['txt', 'text'],
        mpge: ['mp3', 'mp4'],
        pdf: ['pdf'],
        png: ['png'],
        folder: ['folder'],
        lockfolder: ['lockfolder']
      },
      // 预览相关
      excel_tabales: [],
      activeIndex: '0',
      fileLists: [],
      file_new_names: {},
      folder_fileNewname: '',
      viewHtml: { html: '', excel: [] },
      // 显示预览框
      preview_show: false,
      show_pr_type: 'word',
      pdf_url: '',
      currentPage: 0,
      pageCount: 0,
      nowPdfPage: 1,
      // contextmenu data (菜单数据)
      contextMenuData: {
        // the contextmenu name(@1.4.1 updated)
        menuName: 'demo',
        // The coordinates of the display(菜单显示的位置)
        axis: {
          x: null,
          y: null
        },
        // Menu options (菜单选项)
        menulists: [
          {
            fnHandler: 'downloadFile', // Binding events(绑定事件)
            // icoName: "el-icon-s-tools", // icon (icon图标 )
            btnName: '下载' // The name of the menu option (菜单名称)
          },
          {
            fnHandler: 'renameFile',
            // icoName: "el-icon-user",
            btnName: '重命名'
          },
          {
            fnHandler: 'deleteFile',
            // icoName: "el-icon-user",
            btnName: '删除'
          },
          {
            fnHandler: 'previewImg',
            // icoName: "el-icon-user",
            btnName: '预览'
          },
          {
            fnHandler: 'AssignPermissions',
            // icoName: "el-icon-user",
            btnName: '分配权限'
          }
        ]
      },
      diasbleInput: true,
      fileList: [], // 文件列表数组
      showIconTable: false, // 文件是否以表格展示
      showIconList: true, // 文件是否以列表展示
      newFolderDialog: false, // 新建文件夹弹框
      reNameDialog: false, // 重命名弹框
      uploadFileDialog: false, // 上传弹框
      dialogTitle: '新建文件夹', // dialog标题
      directoryPath: '', // 上一级目录
      currentDirectory: '', // 当前目录
      folderInfo: {
        name: '', // 文件夹名字
        roles: [] // 分配角色
      },
      displayPer: false, // 新建文件夹是否显示分配角色
      sonIndex: 0, // 右键菜单方法接受index
      userPermissions: '', // 用户权限数组
      roleList: [], // 角色
      is_admin: false,
      images: [],
      updateFileName: '',
      photo: null,
      description: '',
      productId: 0,
      // 添加头部请求
      headers: {
        Authorization: 'Bearer ' + getToken(),

        post: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      },
      uploadAction: '/adminapi/folder/insertFile',
      url: ''
    }
  },
  computed: {
    // 计算属性的 getter
    limit_file_type: function() {
      const limit_file_type = []
      for (const i in this.file_types) {
        this.file_types[i].forEach(_type => {
          if (_type != 'folder') {
            limit_file_type.push('.' + _type)
          }
        })
      }

      // `this` 指向 vm 实例
      return limit_file_type
    }
  },
  created() {
    this.getFolderList()
    this.getUserInfo()
  },
  methods: {
    canelLog() {
      this.logDialog = false
    },
    selectFileLog() {
      // console.log(value);
      new Promise((resolve, reject) => {
        selectFileLog({ log: this.selectLog }).then(response => {
          this.activities = response.data
        })
      })
    },
    // 查看操作日志
    watchLog() {
      this.logDialog = true
      this.selectLog = '1'
      this.selectFileLog()
    },
    // 文件夹分配权限
    AssignPermissions() {
      // 是否具有分配角色权限
      if (this.isPower('assign folder')) {
        // 在文件管理根目录创建文件夹　显示分配角色
        if (this.currentDirectory == '/fileManagement') {
          this.assignDialog = true
          const fileName = this.fileList[this.sonIndex].fileName
          new Promise((resolve, reject) => {
            getRoles().then(response => {
              // 填充数据
              this.roleList = response.data
              // 判断是否是管理员 如果是的话 显示分配给管理员 否则不显示管理员角色
              if (!this.is_admin) {
                for (let i = 0; i < this.roleList.length; i++) {
                  if (this.roleList[i].name == 'administrator') {
                    this.roleList.splice(i, 1)
                  }
                }
              }
              // 获取当前文件夹拥有的角色
              selectRoles({ fileName: fileName }).then(response => {
                const arr = response.data.folder_belongs_to_many
                for (let i = 0; i < arr.length; i++) {
                  this.assignPer.roles.push(arr[i].id)
                }
              })
            })
          })
        } else {
          this.$message({
            type: 'error',
            message: '请选择一级文件目录分配角色!'
          })
        }
      } else {
        this.$message({
          type: 'error',
          message: '没有分配角色权限,请联系管理员!'
        })
      }
    },
    confirmAssign() {
      const fileName = this.fileList[this.sonIndex].fileName
      return new Promise((resolve, reject) => {
        updateAssign({ roles: this.assignPer.roles, fileName: fileName }).then(
          response => {
            this.getFolderList()
            this.assignDialog = false
          }
        )
      })
    },
    cancelAssign() {
      this.assignDialog = false
      this.assignPer.roles = []
    },
    handleSelect(key, keyPath) {
      // console.log(key, keyPath);
      this.viewHtml.excel = this.excel_tabales[key]
    },
    // 图片预览数组
    pushImage(fileList) {
      const arr = []
      for (let i = 0; i < fileList.length; i++) {
        switch (fileList[i].type) {
          case 'folder':
            arr.push('1')
            break
          case 'png':
            arr.push(fileList[i].url)
            break
          case 'jpeg':
            arr.push(fileList[i].url)
            break
          case 'jpg':
            arr.push(fileList[i].url)
            break
          default:
            arr.push('1')
        }
        this.images = arr
      }
    },
    // 关闭预览框
    handleClosePreview() {
      this.preview_show = false
    },
    // 取消重命名框
    canelReName() {
      this.reNameDialog = false
    },
    // 文件重命名提交
    confirmReName() {
      new Promise((resolve, reject) => {
        updateFileName({
          file: this.fileList[this.sonIndex],
          updateName: this.updateFileName
        }).then(response => {
          this.reNameDialog = false
          this.selectFolder(this.currentDirectory)
        })
      })
    },
    // 鼠标选中文件改变背景颜色
    changeBg(index) {
      let num
      for (let i = 0; i < this.fileList.length; i++) {
        if (i === index) {
          num = i
        } else {
          this.fileList[i].active = 0
        }
      }
      this.fileList[num].active = 1
    },
    // 判断是否具有某某权限
    isPower(Permission) {
      for (let i = 0; i < this.userPermissions.length; i++) {
        if (this.userPermissions[i] == Permission) {
          return true
        }
      }
      return false
    },
    // 下载文件
    downloadFile() {
      // 有权限执行下载 否则提示没有权限
      if (this.isPower('download file')) {
        const url = this.fileList[this.sonIndex].url
        const name = this.fileList[this.sonIndex].fileName
        // console.log(name);
        // console.log(url);
        // console.log(this.fileList);
        const x = new XMLHttpRequest()
        x.open('GET', url, true)
        x.responseType = 'blob'
        x.onload = function() {
          const urls = window.URL.createObjectURL(x.response)
          const a = document.createElement('a')
          a.href = urls
          a.download = name
          a.click()
        }
        x.send()
      } else {
        this.$message({
          type: 'error',
          message: '没有下载文件权限,请联系管理员!'
        })
      }
    },
    inited(viewer) {
      this.$viewer = viewer
    },
    // 预览图片
    previewImg() {
      if (this.isPower('preview file')) {
        if (this.fileList[this.sonIndex].type == 'folder') {
          this.$message({
            type: 'info',
            message: '文件夹不能预览!'
          })
        } else if (
          this.fileList[this.sonIndex].type == 'png' ||
          this.fileList[this.sonIndex].type == 'jpg' ||
          this.fileList[this.sonIndex].type == 'jpeg'
        ) {
          const arr = []
          arr.push(this.fileList[this.sonIndex].url)
          this.images = arr
          this.$viewer.view(0)
        } else {
          this.$message({
            type: 'info',
            message: '当前类型不支持预览!'
          })
        }
      } else {
        this.$message({
          type: 'error',
          message: '没有预览权限,请联系管理员!'
        })
      }
    },
    // 点击重命名按钮方法
    renameFile() {
      if (this.isPower('rename file')) {
        this.reNameDialog = true
        // 判断是文件还是文件夹 文件截取后缀名前面的
        if (this.fileList[this.sonIndex].is_dir == '2') {
          // 截取文件后缀名前面的字符串
          const str = this.fileList[this.sonIndex].fileName.lastIndexOf('.')
          this.updateFileName = this.fileList[this.sonIndex].fileName.substring(
            0,
            str
          )
        } else {
          this.updateFileName = this.fileList[this.sonIndex].fileName
        }
      } else {
        this.$message({
          type: 'error',
          message: '没有重命名权限,请联系管理员!'
        })
      }
    },
    // 右键菜单删除文件
    deleteFile() {
      if (this.isPower('delete file')) {
        this.$confirm('确认删除该文件吗?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          new Promise((resolve, reject) => {
            deleteFolder({ file: this.fileList[this.sonIndex] }).then(
              response => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.selectFolder(this.currentDirectory)
              }
            )
          })
        })
      } else {
        this.$message({
          type: 'error',
          message: '没有删除权限,请联系管理员!'
        })
      }
    },
    // uploadFile(){
    //   console.log(4);
    // },
    // 打开右键菜单
    showMenu(item, index) {
      if (item.type !== 'lockfolder') {
        this.sonIndex = index // 子组件存储下标
        event.preventDefault()
        var x = event.clientX
        var y = event.clientY
        this.contextMenuData.axis = {
          x,
          y
        }
        let num
        // 点击当前文件 添加active 属性 添加样式
        for (let i = 0; i < this.fileList.length; i++) {
          if (i === index) {
            num = i
          } else {
            this.fileList[i].active = 0
          }
        }
        this.fileList[num].active = 1
      } else {
        if (this.isPower('assign folder')) {
          this.sonIndex = index // 子组件存储下标
          event.preventDefault()
          var x = event.clientX
          var y = event.clientY
          this.contextMenuData.axis = {
            x,
            y
          }
          let num
          // 点击当前文件 添加active 属性 添加样式
          for (let i = 0; i < this.fileList.length; i++) {
            if (i === index) {
              num = i
            } else {
              this.fileList[i].active = 0
            }
          }
          this.fileList[num].active = 1
        }
      }
    },
    // 上传前文件类型判断
    beforeUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      let is_overflow = 1
      this.limit_file_type.forEach((item, index) => {
        if (item == '.' + testmsg) {
          is_overflow = 0
        }
      })
      if (is_overflow) {
        this.$message({
          message:
            '上传文件只能是 ' +
            this.limit_file_type.toString().replace(/\./g, '') +
            '格式!',
          type: 'error'
        })
      }

      return !is_overflow
    },
    // 上传文件到当前目录
    uploadSectionFile(param) {
      // console.log("uplodad");
      // console.log(param.file.uid);debugger;
      // console.log(this.file_new_names[param.file.uid]);debugger;
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append(
        'file_new_names',
        this.file_new_names[param.file.uid]
          ? this.file_new_names[param.file.uid]
          : ''
      )
      formData.append('currentDirectory', this.currentDirectory)
      new Promise((resolve, reject) => {
        insertFile(formData)
          .then(response => {
            param.onSuccess(response.data)
            this.uploadFileDialog = false
            // 上传成功后查询当前目录文件和子目录
            this.$refs.upload.clearFiles()
            this.selectFolder(this.currentDirectory)
          })
          .catch(err => {
            this.handleRemove(param.file)
          })
      })
    },
    // 选择文件发生变化钩子
    handleChangeFile() {
      this.fileLists = this.$refs.upload.$children[0].fileList
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    // 获取文件返回路径
    getFilePath(res) {
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
    },
    // 提交上传弹窗
    confirmUpload() {
      this.uploadFileDialog = false
      // 取消当前上传文件的列表
      this.$refs.upload.clearFiles()
    },
    // 取消上传弹窗
    cancelUpload() {
      this.uploadFileDialog = false
      this.$refs.upload.clearFiles()
    },
    // 上传方法
    uploadFile() {
      this.uploadFileDialog = true
      this.file_new_names = {}
      this.fileLists = []
    },
    // 返回上一级方法
    backUp() {
      if (this.directoryPath == '/') {
        this.$message({
          type: 'info',
          message: '已经在最上级了!'
        })
      } else {
        this.selectFolder(this.directoryPath)
      }
    },

    // 根据路径查询文件列表
    selectFolder(directory) {
      // 如果路径去根目录调用getFolderList方法
      if (directory == '/fileManagement') {
        this.getFolderList()
        return
      }
      return new Promise((resolve, reject) => {
        backUpDirectory({ directory: directory }).then(response => {
          this.fileList = response.data
          if (this.fileList == null || this.fileList == '') {
            return null
          }
          // 截取掉  / 后面的内容
          this.directoryPath = this.fileList[0].directory.substring(
            this.fileList[0].directory.lastIndexOf('/'),
            -1
          )
          this.pushImage(this.fileList)
          // 如果当前目录为空 让上一级目录变为  /
          if (this.directoryPath == null || this.directoryPath == '') {
            this.directoryPath = '/'
          }
          this.currentDirectory = this.fileList[0].directory
        })
      })
    },
    // 双击事件
    dbClick(directory, fileName, is_dir, index = 0, type) {
      // 判断是否是文件夹
      if (is_dir == '1') {
        if (type == 'lockfolder') {
          this.$message({
            type: 'error',
            message: '没有权限打开该文件夹'
          })
        } else {
          new Promise((resolve, reject) => {
            openDirectory({ directory: directory, fileName: fileName }).then(
              response => {
                this.fileList = response.data
                this.directoryPath = directory
                this.currentDirectory = directory + '/' + fileName
                this.pushImage(this.fileList)
              }
            )
          })
        }
      }

      // 双击预览文件
      if (is_dir == '2') {
        const preview_loading = this.$loading({
          lock: true,
          text: '加载中'
        })

        if (
          this.fileList[index].type == 'png' ||
          this.fileList[index].type == 'jpg' ||
          this.fileList[index].type == 'jpeg'
        ) {
          // console.log(this.fileList[this.sonIndex].url);
          const arr = []
          arr.push(this.fileList[index].url)
          this.images = arr

          this.$viewer.view(0)
          preview_loading.close()
        } else if (
          this.fileList[index].type == 'doc' ||
          this.fileList[index].type == 'docx'
        ) {
          var mammoth = require('mammoth')

          // mammoth
          //   .convertToHtml({ path: this.fileList[index].url })
          //   .then(function (result) {
          //     var html = result.value; // The generated HTML
          //     var messages = result.messages; // Any messages, such as warnings during conversion
          //   })
          //   .done();
          const _self = this
          const xhr = new XMLHttpRequest()
          xhr.open('get', this.fileList[index].url, true)
          // xhr.open("get", "/fileManagement/4/大成备注.docx", true);
          // xhr.open("get", "/fileManagement/4/锐晶(1).docx", true);
          xhr.responseType = 'arraybuffer'
          xhr.onload = function() {
            if (xhr.status == 200) {
              var options = {
                styleMap: [
                  "p[style-name='Section Title'] => h1:fresh",
                  "p[style-name='Subsection Title'] => h2:fresh",
                  'b => em',
                  'i => strong',
                  'strike => del',
                  'comment-reference => sup'
                ],
                convertImage: mammoth.images.imgElement(function(image) {
                  return image.read('base64').then(function(imageBuffer) {
                    return {
                      src:
                        'data:' + image.contentType + ';base64,' + imageBuffer
                    }
                  })
                })
              }

              mammoth
                .convertToHtml(
                  { arrayBuffer: new Uint8Array(xhr.response) },
                  options
                )
                .then(function(resultObject) {
                  _self.preview_show = true
                  _self.show_pr_type = 'word'
                  _self.$set(_self.viewHtml, 'html', resultObject.value)
                  preview_loading.close()

                  // _self.$nextTick(() => {
                  //   // document.querySelector("#wordView").innerHTML =
                  //   //   resultObject.value;

                  //   _self.$set(this.viewHtml,'html', resultObject.value)
                  // });
                })
            }
          }
          xhr.send()
        } else if (this.fileList[index].type == 'pdf') {
          const hostname = document.location.host
          const _self = this
          _self.preview_show = true
          this.pdf_url = 'http://' + hostname + this.fileList[index].url
          this.show_pr_type = 'pdf'
          preview_loading.close()
        } else if (this.fileList[index].type == 'txt') {
          const _self = this
          const xhr = new XMLHttpRequest()
          xhr.open('get', this.fileList[index].url, true)
          // xhr.open("get", "/fileManagement/4/大成备注.docx", true);
          // xhr.open("get", "/fileManagement/4/锐晶(1).docx", true);
          xhr.responseType = 'text'
          xhr.onload = function() {
            if (xhr.status == 200) {
              const res_text = xhr.response.replace(/\n/g, '<br>')
              _self.preview_show = true
              _self.show_pr_type = 'word'
              _self.$set(_self.viewHtml, 'html', res_text)
              preview_loading.close()
            }
          }
          xhr.send()
        } else if (
          this.fileList[index].type == 'xls' ||
          this.fileList[index].type == 'xlsx'
        ) {
          // excel
          const _self = this
          analysisExcel({ file_neme: this.fileList[index].url })
            .then(response => {
              _self.preview_show = true
              _self.show_pr_type = 'excel'
              _self.viewHtml.excel = response.data[0]
              _self.excel_tabales = response.data
              preview_loading.close()
            })
            .catch(err => {
              preview_loading.close()
            })
        } else {
          preview_loading.close()
          this.$message({
            type: 'info',
            message: '当前类型文件不支持预览!'
          })
        }
      }
    },

    // 根据返回的数据类型显示不同的图片
    getIconUrl(type) {
      const types_icon_arr = this.file_types
      let show_tyupe = 'none'
      for (const i in types_icon_arr) {
        types_icon_arr[i].forEach(_type => {
          if (type == _type) {
            // console.log(type);
            show_tyupe = i
          }
        })
      }
      return require('@/assets/resourse/' + show_tyupe + '.png')
    },

    // 获取文件夹和目录列表
    getFolderList() {
      new Promise((resolve, reject) => {
        getFolder().then(response => {
          this.fileList = response.data
          this.directoryPath = '/'
          if (this.fileList == null || this.fileList == '') {
            this.currentDirectory = '/fileManagement'
          } else {
            this.currentDirectory = this.fileList[0].directory
          }
        })
      })
    },

    // 取消dialog
    cancelFolder() {
      this.newFolderDialog = false
      this.folderInfo.name = ''
      this.folderInfo.roles = ''
    },
    // 新建文件夹信息
    confirmFolder() {
      if (this.dialogTitle == '新建文件夹') {
        new Promise((resolve, reject) => {
          insertFolder({
            folderInfo: this.folderInfo,
            directory: this.currentDirectory
          }).then(response => {
            this.$message({
              type: 'success',
              message: '新建文件夹成功!'
            })
            this.newFolderDialog = false
            this.selectFolder(this.currentDirectory)
          })
        })
      } else {
      }
    },
    // 点击新建文件夹按钮
    newFloderClick() {
      if (this.isPower('insert file')) {
        this.dialogTitle = '新建文件夹'
        this.newFolderDialog = true
        // 是否具有分配角色权限
        if (this.isPower('assign folder')) {
          // 在文件管理根目录创建文件夹　显示分配角色
          if (this.currentDirectory == '/fileManagement') {
            this.displayPer = true
            new Promise((resolve, reject) => {
              getRoles().then(response => {
                // 填充数据
                this.roleList = response.data
                // 判断是否是管理员 如果是的话 显示分配给管理员 否则不显示管理员角色
                if (!this.is_admin) {
                  for (let i = 0; i < this.roleList.length; i++) {
                    if (this.roleList[i].name == 'administrator') {
                      this.roleList.splice(i, 1)
                    }
                  }
                }
              })
            })
          } else {
            this.displayPer = false
          }
        }
      } else {
        this.$message({
          type: 'error',
          message: '没有新建文件夹权限,请联系管理员!'
        })
      }
    },
    // 将文件以列表展示
    clickIconList() {
      this.showIconList = !this.showIconList
      this.showIconTable = !this.showIconTable
    },
    // 将文件以表格类型显示
    clickIconTable() {
      this.showIconTable = !this.showIconTable
      this.showIconList = !this.showIconList
    },
    // 上传失败
    handleError(err, file, fileList) {
      // console.log(err);
      this.$message({
        type: 'error',
        message: '上传失败,请重新上传!'
      })
    },
    // 下载
    handleDownload($index, row) {},
    // 文件预览
    handlePreview() {},
    // 文件移除
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    // 文件限制
    handleExceed(files, fileList) {
      this.$message.warning(`一次最多只可上传3个文件`)
    },
    // 文件移除前
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then(response => {
          // this.username = response.data.name; //当前登录用户的姓名
          this.userPermissions = response.data.per // 当前登录用户权限数组
          for (let i = 0; i < this.userPermissions.length; i++) {
            if (this.userPermissions[i] == 'update power') {
              this.is_admin = true
            }
          }
        })
      })
    }
  }
}
</script>

<style>
.fileBox .container {
  /* width: 100%; */
  margin: 10px;
  /* border: 1px solid red; */
  display: grid;
  grid-row-gap: 20px;
  grid-column-gap: 20px;
  grid-template-columns: repeat(auto-fill, 100px);
  /* grid-template-rows: repeat(auto-fill, 100px); */
}

.fileBox .container .box {
  /* border: 1px solid red; */
  width: 112px;
  height: 136px;
  margin: 5px;
  padding: 10%;
}
.fileBox .container .box .iconBox {
  width: 100%;
  height: 80px;
  text-align: center;
}
.fileBox .el-scrollbar .el-scrollbar__wrap {
  overflow-x: hidden;
  max-height: 300px;
  padding: 10px;
  /* height: 300px; */
}

.fileBox .container .box .fileText {
  width: 100%;
  margin-top: 10px;
  text-align: center;
  height: 23px;
  line-height: 23px;
  color: #595c5f;
  font-size: 15px;
}
.fileBox .fileInput .el-input__inner {
  text-align: center;
  height: 25px;
  margin-top: 5px;
  border: none;
}
.fileBox .tableList {
  margin: 10px;
}

.fileBox .logDialog .el-dialog .el-dialog__body {
  padding: 0px 10px 10px 10px;
}

.fileBox .el-dialog .el-dialog__body {
  padding: 0px 20px 0px 20px;
}
.fileBox .el-form-item__content .el-input .el-input__inner {
  height: 30px;
  line-height: 30px;
}
.fileBox .el-form-item {
  margin-bottom: 10px;
}
.fileBox .operation {
  padding: 10px;
  margin: 10px;
  width: 100%;
  margin-right: 10px;
  display: inline-block;
  -webkit-box-shadow: 6px 6px 15px rgba(0, 0, 0, 0.3);
  box-shadow: 6px 6px 15px rgba(0, 0, 0, 0.3);
}
.fileBox .icon {
  font-size: 20px;
  cursor: pointer;
  color: #00abea;
  line-height: 32px;
  padding-right: 30px;
}
.fileBox .box .vue-contextmenuName-demo {
  margin: 0;
  padding: 0;
  width: 130px;
  text-align: center;
}
.fileBox .box .vue-contextmenuName-demo .btn-wrapper-simple {
  height: 30px;
  line-height: 30px;
  align-items: center;
}
.fileBox .box .nav-name-right {
  font-size: 14px;
  font-family: "微软雅黑";
  color: #333;
  text-align: center;
  line-height: 20px;
  display: block;
}
.fileBox .box .context-menu-list :hover {
  background: #ccc;
}
.fileBox .el-input.is-disabled .el-input__inner {
  background: none;
  color: #595c59;
}
.fileBox .active {
  background: #eff3f9 none repeat scroll 0 0;
  border-color: #bcccde;
  border-radius: 10px;
}
.fileBox .image {
  display: none;
}
.fileBox .viewHtml_box img {
  max-width: 100%;
}
.fileBox .upload-input .el-upload--text,
.upload-input .el-upload-dragger {
  width: 100%;
}
.fileBox .folder_fileNewname_form label.el-form-item__label {
  text-align: left;
  overflow: hidden;
  word-break: keep-all;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.fileBox .show_excel .el-dialog {
  width: 1500px !important;
}
.fileBox .show_excel .el-dialog table {
  margin: 0px;
}
.fileBox .show_excel .table-header {
  background: #ccc;
}
.fileBox .show_excel .table-header td {
  border: 0;
}
.fileBox .timeLine span {
  margin: 2px;
}
.fileBox .selectDiv {
  padding-right: 40px;
  text-align: right;
}
.fileBox .selectInput .el-input__inner {
  width: 120px;
}
</style>
